import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    meta: { requiresAuth: false }
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: { requiresAuth: true },
    redirect: '/home/dashboard',
    children: [
      {
        path: 'dashboard',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue')
      },
      {
        path: 'signal-monitor',
        name: 'SignalMonitor',
        component: () => import('../views/SignalMonitor.vue')
      },
      {
        path: 'device-management',
        name: 'DeviceManagement',
        component: () => import('../views/DeviceManagement.vue')
      },
      {
        path: 'task-management',
        name: 'TaskManagement',
        component: () => import('../views/TaskManagement.vue')
      },
      {
        path: 'result-analysis',
        name: 'ResultAnalysis',
        component: () => import('../views/ResultAnalysis.vue')
      },
      {
        path: 'user-management',
        name: 'UserManagement',
        component: () => import('../views/UserManagement.vue')
      }
    ]  
  },
  // 访问无关路由
  {
    path: '/:pathMatch(.*)*',
    redirect: '/home/dashboard'
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  
  // 如果路由需要认证
  if (to.meta.requiresAuth) {
    if (!token) {
      // 没有token，跳转到登录页
      next('/login')
    } else {
      // 有token，允许访问
      next()
    }
  } else {
    // 不需要认证的路由，直接放行
    next()
  }
})

export default router